<template>
  <BasicDrawer v-bind="$attrs" @register="registerDrawer" showFooter :title="getTitle" width="80%" @ok="handleSubmit">

    <BasicForm @register="registerForm">

      <template #options="{ model, field }">
        <vxe-grid ref="tableRef" v-bind="gridOptions">
          <template #toolbar_buttons>
            <Button type="primary" size="small" @click="addFn">新增选项</Button>
          </template>
          <template #action="{ row }">
            <TableAction outside :actions="getActions(row)" />
          </template>
        </vxe-grid>
      </template>
      <template #infos="{ model, field }">
        <div v-if="publishPapers.length>0">
          <div>该题目有答题记录并已结算分数；修改正确选项后，可开启'同步分数'->'确认'来重新计算该题目的分数！</div>
          <a v-if="exUserPapers.length>0" @click="applyViewOpen">已同步:{{exUserPapers.length}}</a>
          <vxe-list class="my-table-list"  :data="publishPapers" :virtual-y-config="{enabled: true, gt: 0, sItem: '.my-tr'}" size="mini">
            <template #default="{ items }">
              <table>
                <thead>
                <tr>
                  <th>试卷名称</th>
                  <th>开考时间</th>
                  <th style="color: #e03e2d">同步分数</th>
                </tr>
                </thead>
                <tbody>
                <tr class="my-tr" v-for="item in items" :key="item.publishPaperId">
                  <td>{{ item.paperName }}</td>
                  <td>{{ item.startTime}}</td>
                  <td><vxe-switch v-model="item.izSync"></vxe-switch></td>
                </tr>
                </tbody>
              </table>
            </template>
          </vxe-list>

        </div>
        <div v-else>暂无</div>

      </template>


    </BasicForm>

    <Modal v-model:visible="applyViewShow" title="同步分数结果" @ok="applyViewClose">
      <div>同步完毕，以下为同步后的人员分数！查看更详情答题情况，请前往'试卷发布管理'-查看答题 按钮点击</div>

      <vxe-list class="my-table-list"  :data="exUserPapers" :virtual-y-config="{enabled: true, gt: 0, sItem: '.my-tr'}" size="mini">
        <template #default="{ items }">
          <table>
            <thead>
            <tr>
              <th>试卷名称</th>
              <th>姓名</th>
              <th>分数</th>
              <th>开考时间</th>
              <th>查看</th>
            </tr>
            </thead>
            <tbody>
            <tr class="my-tr" v-for="item in items" :key="item.userPaperId">
              <td>{{ item.paperName }}</td>
              <td>{{ item.userName  }}</td>
              <td>{{ item.score  }}</td>
              <td>{{ item.createTime}}</td>
              <td>
                <TableAction outside :actions="[
                {
                  label:'查看答题',
                  onClick: openUserAnserFn.bind(null, item),
                }
            ]
        " />
              </td>
            </tr>
            </tbody>
          </table>
        </template>
      </vxe-list>

    </Modal>

    <UserAnserLogDrawer @register="userAnser[0]"></UserAnserLogDrawer>

  </BasicDrawer>
</template>
<script lang="ts" setup>
import { ref, computed, unref, h, toRaw, reactive } from 'vue';
import { BasicForm, useForm } from '@/components/Form';
import {Button, Modal} from 'ant-design-vue';
import { TableAction } from '@/components/Table';


import {
  formSchema, optionColumns
} from './role.data';

import {BasicDrawer, useDrawer, useDrawerInner} from '@/components/Drawer';
import { Form, FormItem, Input, InputNumber, DatePicker, Select, Switch } from 'ant-design-vue';

import {questionSave, questionOptions, getAnsersPublishPaper,againCountQuestionScoreFn} from '@/api/heng/ex';

import {
  BasicTableProps,
  VxeBasicTable,
  VxeGridInstance,
  VxeGridListeners,
  VxeTableDefines,
} from '@/components/VxeTable';


import { useMessage } from "@/hooks/web/useMessage";
import util from '@/utils/util';
import UserAnserLogDrawer from "@/views/ex/publish/UserAnserLogDrawer.vue";

const emit = defineEmits(['success', 'register']);
const isUpdate = ref(true);
const { createMessage } = useMessage();


const id = ref("")

const options = ref([]);

const publishPapers=ref([]);//已发布试卷

const applyViewShow = ref(false);
const exUserPapers=ref([]);
const userAnser= useDrawer();

const tableRef = ref();

const gridOptions = reactive<BasicTableProps>({
  // keepSource: true,
  editConfig: { trigger: 'click', mode: 'cell', showStatus: true },
  border: true,
  showOverflow: true,
  size: 'mini',
  height: 'auto', // 'auto'
  columns: optionColumns,
  filterConfig: {
    remote: true,
  },

  toolbarConfig: {
    slots: {
      buttons: 'toolbar_buttons',
    },
    refresh: true,
  },
  formConfig: {
    // enabled: true,
  },
  pagerConfig: {
    // pageSize: 20,
  },
  proxyConfig: {
    enabled: false,
  },
});

const [registerForm, { resetFields, setFieldsValue, updateSchema, validate }] = useForm({
  labelWidth: 100,
  schemas: formSchema,
  showActionButtonGroup: false,
  baseColProps: { lg: 12, md: 24 },
});


const dataList = ref({});


const [registerDrawer, { setDrawerProps, closeDrawer }] = useDrawerInner(async (data) => {
  //打开弹层后的回调
  // resetFields();
  setDrawerProps({ confirmLoading: false });
  isUpdate.value = !!data?.isUpdate;
  id.value = "";
  if (!isUpdate.value) {
    resetFields();
    dataList.value = [];
    tableRef.value.reloadData([]);
  } else {
    dataList.value = data.record;
    id.value = data.record.questionId;
    if(data.record.img){
      data.record.imgArr=data.record.img.split(',');
    }
    setFieldsValue(data.record);
    getQuestionOptions();
    getAnsersPublishPaperFn();
  }

});

const getTitle = computed(() => ('题目编辑'));


//async function handleSubmit()
function getIzSync(){
  let publishPaperId=[];
  for(let i = 0; i < publishPapers.value.length; i++){
    let valueElement = publishPapers.value[i];
    if(valueElement.izSync){
      publishPaperId.push(valueElement.publishPaperId);
    }
  }
  return publishPaperId;
}

async function handleSubmit() {
  try {
    let idArr = getIzSync();

    let t_list = tableRef.value.getTableData().tableData;
    // console.log("---t_list:", t_list);
    if (t_list.length == 0) {
      createMessage.error("请添加选项");
      return;
    }
    const values = await validate();
    values.questionId = id.value;
    values.options = t_list;
    if(values.imgArr){
      values.img=values.imgArr.join(",");
    }
    questionSave(values).then(res => {
      if(res.code==200){
        if(idArr.length>0){
          let json={
            questionId : id.value,
            publishPaperId: idArr.join(",")
          }
          againCountQuestionScoreFn(json).then((re) => {
            if(re.code==200){
              createMessage.success("同步分数成功");
              // sunccFn(res);
               exUserPapers.value=re.data;
               applyViewOpen();
            }else{
              createMessage.error(re.message);

            }
          })
        }else{
          sunccFn(res)
        }
      }else{
        createMessage.error(res.message);
      }

    });


  } catch (e) {
    console.log(e)
  } finally {
    setDrawerProps({ confirmLoading: false });

  }
}

function sunccFn(result) {
  if (result && result.code == 200) {
    createMessage.success(result.message);
  } else {
    createMessage.error(result.message);
  }
  closeDrawer()
  emit('success');
}

function cancelFn() {
  //  tableRef.value.clearValidate();
}

function getQuestionOptions() {
  questionOptions({ questionId: id.value }).then(res => {
    if (res.code == 200) {
      options.value = res.data;
      tableRef.value.reloadData(res.data);
    } else {
      createMessage.error(result.message);

    }

  });
}


function getAnsersPublishPaperFn() {
  getAnsersPublishPaper({ questionId: id.value }).then(res => {
    if (res.code == 200) {
      publishPapers.value = res.data;
      //  dataList.value.showInfo=true;
      // setFieldsValue(dataList.value);
    } else {
      createMessage.error(result.message);

    }

  });
}



function addFn() {
  tableRef.value.insertAt({ questionId: id.value, isTrue: 0 }, -1);
}

function getActions(record) {
  let arr = [

    {
      // icon: 'ant-design:delete-outlined',
      label: '删除',
      color: 'error',
      popConfirm: {
        title: '是否删除？',
        placement: 'left',
        confirm: handleClose.bind(null, record),
      },
    }
  ];


  return arr;
}

function handleClose(record: Recordable) {

  tableRef.value.remove(record);
  //console.log(record);

  // questionRemove(record)
  //   .then((res) => {
  //     if (res.code == 200) {
  //       createMessage.success(res.message);
  //       tableRef.value.commitProxy('reload');

  //     } else {
  //       createMessage.error(res.message);

  //     }

  //   })
  //   .catch((res) => {
  //     createMessage.error(res.message);
  //   })
  //   .finally(() => {
  //   });
}


function applyViewOpen() {
  applyViewShow.value = true;
}

function applyViewClose() {
  applyViewShow.value = false;
}


function openUserAnserFn(record: Recordable) {
  userAnser[1].openDrawer(true, record);
}

</script>
<style lang="less">
.item-row {
  margin: 0 auto;

  //padding-left: 5%;
  .ant-form-item-label {
    flex: 0 0 28.5%;
    max-width: 28.5%;
  }
}

.lqfp-8 {
  //padding-left: 9% !important;

}

.my-table-list {
  border: 1px solid #e8eaec;
  table {
    width: 100%;
    text-align: center;
    border-spacing: 0;
  }
  tr {
    //height: 30px;
    &:hover {
      background-color: #f5f7fa;
    }
  }
  th {
    //height: 40px;
    background-color: #f8f8f9;
    position: sticky;
    top: 0;
  }
  th,
  td {
    border-bottom: 1px solid #e8eaec;
    border-right: 1px solid #e8eaec;
  }
}

.mybg {
  line-height: 30px;
  text-align: center;
}

</style>
